package cn.ymatrix.readFromYMatrix;

import cn.ymatrix.logger.LoggerLevel;
import cn.ymatrix.logger.MxLogger;
import cn.ymatrix.utils.Config;
import org.slf4j.Logger;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCReadFromYMatrix {
  public static void main(String[] args) {

    MxLogger.loggerLevel(LoggerLevel.INFO);
    Logger LOGGER = MxLogger.init(JDBCReadFromYMatrix.class);

    String sql =
        "SELECT * FROM "
            + Config.getTableName()
            + "order by ts  desc OFFSET 4 FETCH FIRST 6 ROWS ONLY";
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    try {
      Class.forName(Config.getDRIVER_CLASS_NAME());
      connection = Config.getDateSource().getConnection();
      connection.setAutoCommit(true);

      statement = connection.createStatement();
      resultSet = statement.executeQuery(sql);
      int index = 0;
      while (resultSet.next()) {
        index++;
        String ts = resultSet.getString("ts");
        String t1 = resultSet.getString("t1");
        String t2 = resultSet.getString("t2");
        LOGGER.info(" ts = " + ts + " , t1 = " + t1 + " , t2 = " + t2);
      }
    } catch (ClassNotFoundException | SQLException e) {
      e.printStackTrace();
    } finally {
      if (resultSet != null) {
        try {
          resultSet.close();
        } catch (SQLException e) {
          LOGGER.error("resultSet close error " + e.getMessage());
          e.printStackTrace();
        }
      }
      if (statement != null) {
        try {
          statement.close();
        } catch (SQLException e) {
          LOGGER.error("statement close  error " + e.getMessage());
        }
      }
      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException e) {
          LOGGER.error("connection close  error " + e.getMessage());
          e.printStackTrace();
        }
      }
    }
  }
}
